package com.example.demo.services.impl;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.dao.ArticleMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Article;
import com.example.demo.services.IArticleService;
import com.example.demo.services.IBoardService;
import com.example.demo.services.IUserService;
import com.example.demo.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;
    @Override
    public List<Article> selectAll() {
        //直接调用DAO
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        //非空校验
        if (boardId == null || boardId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        List<Article> articles = articleMapper.selectByBoardId(boardId);
        //返回结果
        return articles;
    }

    @Override
    public void create(Article article) {
        //非空校验
        if (article == null || article.getBoardId() == null || article.getBoardId() <= 0
                || article.getUserId() == null || article.getUserId() <= 0
                || StringUtils.isEmpty(article.getTitle()) || StringUtils.isEmpty(article.getContent())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0);//访问数量
        article.setReplyCount(0);//回复数
        article.setLikeCount(0);//点赞数
        article.setState((byte) 0);//帖子状态
        article.setDeleteState((byte) 0);//删除状态
        Date date = new Date();
        article.setCreateTime(date);//发布时间
        article.setUpdateTime(date);//更新时间
        //写入数据库
        int row = articleMapper.insertSelective(article);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString() + ",帖子写入失败");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //更新用户发帖数
        userService.addOneArticleCountById(article.getUserId());
        //更新板块中的贴子数
        boardService.addOneArticleCountById(article.getBoardId());
        //打印日志
        log.info("发帖成功：userId = " + article.getUserId() + ", boardId = " + article.getBoardId() + ".");
    }

    @Override
    public Article selectDetailsById(Long id) {
        //非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询帖子详情
        Article article = articleMapper.selectDetailsById(id);
        if(article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //帖子询问数量+1
        article.setVisitCount(article.getVisitCount() + 1);

        //创建用于更新的对象
        Article updateArticle = new Article();//创建用于更新的对象
        updateArticle.setId(article.getId());//设置Id
        updateArticle.setVisitCount(article.getVisitCount());//访问数
        updateArticle.setUpdateTime(new Date());//更新时间
        //调用更新方法
        articleMapper.updateByPrimaryKeySelective(updateArticle);
        //返回成功
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if(id == null || id <= 0 || StringUtils.isEmpty(title)
            || StringUtils.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建一个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);//id
        updateArticle.setTitle(title);//标题
        updateArticle.setContent(content);//正文
        updateArticle.setUpdateTime(new Date());//更新时间

        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString() + ",帖子更新失败，article id = " +id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
    }

    @Override
    public void updateById(Article article) {
        //非空校验
        if (article.getId() == null || article.getId() <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(article);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString() + ",帖子更新失败，article id = " + article);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        // 非空校验
        if (id == null) {
            // 记录日志
            log.info(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 查询帖子信息
        Article article = selectById(id);
        if (article == null || article.getState() == 1 || article.getDeleteState() == 1) {
            // FAILED_NOT_EXISTS
            // 记录日志
            log.info(ResultCode.FAILED_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }

        // 构造更新对象
        Article update = new Article();
        update.setId(article.getId());
        update.setLikeCount(article.getLikeCount() + 1);

        // 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1) {
            // 记录日志
            log.info(ResultCode.ERROR_SERVICES.toString() + "articleId = " + article.getId());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        // 非空校验
        if (id == null) {
            // 记录日志
            log.info(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 查询帖子信息
        Article article = selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            // FAILED_NOT_EXISTS
            // 记录日志
            log.info(ResultCode.FAILED_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }

        // 构造更新对象
        Article update = new Article();
        update.setId(article.getId());
        update.setDeleteState((byte) 1);

        // 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1) {
            // 记录日志
            log.info(ResultCode.ERROR_SERVICES.toString() + "articleId = " + article.getId());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        // 非空校验
        if (userId == null) {
            // 记录日志
            log.info(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 调用DAO层查询结果
        List<Article> result = articleMapper.selectByUserId(userId);
        // 返回结果
        return result;
    }

    @Override
    public Article selectById(Long id) {
        // 非空校验
        if (id == null) {
            // 记录日志
            log.info(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 调用DAO查询结果
        Article result = articleMapper.selectByPrimaryKey(id);
        // 返回结果
        return result;
    }
}
